﻿namespace BEGDC.CC.Web.Common
{
    using System;
    using System.Collections;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.UserManagement;
    using BEGDC.CC.Entity;

    /// <summary>
    ///	Summary description for StampCtrl.
    /// </summary>
    public class StampCtrl : System.Web.UI.UserControl
    {
        protected System.Web.UI.WebControls.Label lblRunFlowRoleName;
        protected System.Web.UI.WebControls.Label lblRunFlowActorsName;
        protected System.Web.UI.WebControls.Label lblRoleNameTip;
        protected System.Web.UI.WebControls.Label lblActorsNameTip;

        #region ActionName

        private const string Submit = "Submit";
        private const string AskForMore = "AskForMore";
        private const string ReplyAskForMore = "ReplyAskForMore";
        private const string Query = "Query";
        private const string ReplyQuery = "ReplyQuery";
        private const string Reject = "Reject";
        private const string Approve = "Approve";
        private const string Assign = "Assign";
        private const string Check = "Check";
        private const string Close = "Close";
        private const string CheckMM = "CheckMM";

        #endregion

        #region Step

        private const string End = "End";
        private const string StepClose = "Close";
        private const string CloseApp = "CloseApp";
        private const string Pending = "Pending";
        private const string ReRequest = "ReRequest";

        #endregion

        #region CRStep

        private const string CRStepCodeCATVPApproval = "CATVPApproval";
        private const string CRStepCodeFNCApproval = "FNCApproval";
        private const string CRStepCodeDeptHeadApproval = "DeptHeadApproval";
        private const string CRStepCodeBDDirectorApproval = "BDDirectorApproval";
        private const string CRStepCodeBDHeadApproval = "BDHeadApproval";
        private const string CRStepCodeCRSurvey = "CRSurvey";
        private const string CRStepDeptDirectorApproval = "DeptDirectorApproval";
        private const string CRStepCloseApp = "CloseApp";

        #endregion

        #region  EVStep

        private const string EVStepCodeClose = "Close";
        private const string EVStepStaffCheckMM = "StaffCheckMM";
        private const string EVStepCATApproveMM = "CATApproveMM";
        private const string EVStepPSOApproveMM = "PSOApproveMM";

        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            //if (this.Request.QueryString["AppID"] != null)
            //{
            //    int appid = Convert.ToInt32(this.Request.QueryString["AppID"]);
            //    this.GetStampByAppID(appid);
            //}
            //else
            //{
            //    this.SetDataSource(new DataTable());
            //}
            this.Visible = false;
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        #region GetAppType

        private int GetAppTypeIDByPDType()
        {
            string appTypeStr = this.Request.QueryString["PDType"];
            IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            return queryService.GetAppTypeID(appTypeStr);
        }

        #endregion

        #region Pendding StampCellList

        private ArrayList StampCellList(ArrayList cellArray, int targetStep)
        {
            IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            int appTypeID = GetAppTypeIDByPDType();

            DataTable table = queryService.QueryActionNextSteps(targetStep, appTypeID);

            if (table != null && table.Rows.Count > 0)
            {
                DataRow[] rows = table.Select();

                for (int i = 0; i < rows.Length; i++)
                {
                    //if (rows[0]["StepCode"].ToString().Equals("End")) break;

                    string stepCode = rows[i]["StepCode"].ToString();

                    if (stepCode == End)
                    {
                        this.lblRoleNameTip.Visible = false;
                        this.lblActorsNameTip.Visible = false;
                        break;
                    }

                    //屏蔽CR的CATVPApproval、FNCApproval、DeptHeadApproval、BDDirectorApproval、BDHeadApproval、CRSurvey
                    if (appTypeID == 1 && (stepCode == CRStepCodeCATVPApproval || stepCode == CRStepCodeFNCApproval || stepCode == CRStepCodeDeptHeadApproval || stepCode == CRStepCodeBDDirectorApproval || stepCode == CRStepCodeBDHeadApproval || stepCode == CRStepCodeCRSurvey))
                        continue;

                    if (!(stepCode == End || stepCode == ReRequest))
                    {
                        if (i == 0)
                        {
                            ////当前需要执行的流程结点
                            this.lblRunFlowRoleName.Text = rows[i]["Description"].ToString();
                            this.SetLblRunFlowActorsName(rows[i]["Description"].ToString(), stepCode, appTypeID);

                            if (stepCode == StepClose || stepCode == CloseApp)
                            {
                                cellArray.Add(this.GetStampCell(stepCode, DateTime.Now.ToString("MM/dd/yyyy"), Pending, "PendingY.gif"));
                                break;
                            } 

                            // EV StaffCheckMM
                            if (appTypeID == 3 && stepCode == EVStepStaffCheckMM)
                            {  
                                cellArray.Add(this.GetStampCell(stepCode, DateTime.Now.ToString("MM/dd/yyyy"), Pending, "PendingY.gif"));
                                cellArray.Add(this.GetStampCell(EVStepCATApproveMM, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                cellArray.Add(this.GetStampCell(EVStepPSOApproveMM, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                cellArray.Add(this.GetStampCell(EVStepCodeClose, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                break;
                            }
                            // CR DeptDirectorApproval
                            else if (appTypeID == 1 && stepCode == CRStepDeptDirectorApproval)
                            {
                                cellArray.Add(this.GetStampCell(stepCode, DateTime.Now.ToString("MM/dd/yyyy"), Pending, "PendingY.gif"));
                                cellArray.Add(this.GetStampCell(CRStepCloseApp, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                break;
                            }
                            else
                            {
                                cellArray.Add(this.GetStampCell(stepCode, DateTime.Now.ToString("MM/dd/yyyy"), Pending, "PendingY.gif"));
                            }


                        }
                        else
                        {
                            //设置 EV StaffCheckMM 位置 
                            if (appTypeID == 3 && stepCode == EVStepCodeClose)
                            {
                                cellArray.Add(this.GetStampCell(EVStepStaffCheckMM, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                cellArray.Add(this.GetStampCell(EVStepCodeClose, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                break;
                            }
                            else if (appTypeID == 1 && stepCode == CRStepCloseApp)
                            {
                                cellArray.Add(this.GetStampCell(CRStepDeptDirectorApproval, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                cellArray.Add(this.GetStampCell(CRStepCloseApp, "xxxx-xx-xx", Pending, "PendingG.gif"));
                                break;
                            }
                            else
                            {
                                cellArray.Add(this.GetStampCell(stepCode, "xxxx-xx-xx", Pending, "PendingG.gif"));
                            }
                        }
                    }

                }
            }
            return cellArray;
        }

        private BEGDC.CC.Web.Common.StampCell GetStampCell(string actorStr, string dateTimeStr, string actionStr, string imageStr)
        {
            BEGDC.CC.Web.Common.StampCell stampCell;
            stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");
            stampCell.SetStampInfo(actorStr, dateTimeStr, actionStr, imageStr, Color.Black);
            return stampCell;
        }

        #endregion

        /// <summary>
        /// 显示已操作过的步骤
        /// </summary>
        private void SetDataSource(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
            {
                DataRow[] rows = table.Select();

                BEGDC.CC.Web.Common.StampCell stampCell;

                ArrayList cellArray = new ArrayList();
                int targetStep = 0;

                for (int i = 0; i < rows.Length; i++)
                {
                    #region Submit
                    //Submit
                    if (rows[i]["ActionName"].ToString() == Submit)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");
                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif", Color.Green);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }

                    #endregion

                    #region Assign

                    if (rows[i]["ActionName"].ToString() == Assign)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");
                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif", Color.Green);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }

                    #endregion

                    #region Check

                    if (rows[i]["ActionName"].ToString() == Check)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");

                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif", Color.Green);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }

                    #endregion

                    #region CheckMM

                    if (rows[i]["ActionName"].ToString() == CheckMM)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");

                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif",Color.Green);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }

                    #endregion

                    #region Approve

                    if (rows[i]["ActionName"].ToString() == Approve)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");

                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif", Color.Green);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }

                    #endregion

                    #region Close

                    if (rows[i]["ActionName"].ToString() == Close)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");

                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif", Color.Green);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }

                    #endregion

                    #region Reject

                    if (rows[i]["ActionName"].ToString() == Reject)
                    {
                        stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");

                        stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Rejected.gif", Color.Red);

                        if (i + 1 < rows.Length)
                        {
                            if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                            {
                                cellArray.Add(stampCell);
                            }
                        }
                        else
                        {
                            cellArray.Add(stampCell);
                        }
                    }
                    #endregion

                    #region Ask For More

                    //if (rows[i]["ActionName"].ToString() == AskForMore)
                    //{
                    //    stampCell = (BEGDC.CC.Web.Common.StampCell)this.LoadControl("stampCell.ascx");

                    //    stampCell.SetStampInfo(rows[i]["Actor"].ToString(), Convert.ToDateTime(rows[i]["ActionDate"]).ToString("MM/dd/yyyy"), rows[i]["ActionName"].ToString(), "Reviewed.gif");

                    //    if (i + 1 < rows.Length)
                    //    {
                    //        if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                    //        {
                    //            cellArray.Add(stampCell);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        cellArray.Add(stampCell);
                    //    }
                    //}

                    #endregion

                    //set targetStep value
                    if (i + 1 < rows.Length)
                    {
                        if (rows[i + 1]["ActionName"].ToString() != "Drawback")
                        {
                            targetStep = (int)table.Rows[i]["TargetStep"];
                        }
                    }
                    else
                    {
                        targetStep = (int)table.Rows[i]["TargetStep"];
                    }


                }
                cellArray = this.StampCellList(cellArray, targetStep);
                this.ControlsAdd(cellArray);
            }
            else
            {
                ArrayList cellArray = new ArrayList();
                cellArray = this.StampCellList(cellArray, 0);
                this.ControlsAdd(cellArray);
            }
        }

        /// <summary>
        /// 结点每行显示7个
        /// </summary>
        /// <param name="cellArray"></param>
        private void ControlsAdd(ArrayList cellArray)
        {
            if (cellArray.Count > 0)
            {
                HtmlTable htmlTable = new HtmlTable();
                htmlTable.Border = 0;
                htmlTable.CellPadding = 0;
                htmlTable.CellSpacing = 0;

                int k;
                if (cellArray.Count % 7 == 0)
                {
                    k = cellArray.Count / 7;
                }
                else
                {
                    k = ((int)cellArray.Count / 7) + 1;
                }

                ArrayList rowArray = new ArrayList();
                for (int m = 0; m < k; m++)
                {
                    HtmlTableRow htmlRow = new HtmlTableRow();
                    rowArray.Add(htmlRow);
                }

                IEnumerator rowEnum = rowArray.GetEnumerator();
                rowEnum.MoveNext();

                for (int j = 0; j < cellArray.Count; j++)
                {
                    HtmlTableCell htmlCell = new HtmlTableCell();

                    htmlCell.Controls.Add((BEGDC.CC.Web.Common.StampCell)cellArray[j]);
                    ((HtmlTableRow)rowEnum.Current).Cells.Add(htmlCell);

                    if (((j + 1) % 7 == 0) || j == cellArray.Count - 1)
                    {
                        htmlTable.Rows.Add(((HtmlTableRow)rowEnum.Current));
                        rowEnum.MoveNext();
                    }
                }

                this.Controls.Add(htmlTable);
            }
        }

        private void GetStampByAppID(int AppID)
        {
            IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            DataTable table = queryService.QueryActionLog(AppID);
            this.SetDataSource(table);
        }

        private void SetLblRunFlowActorsName(string description, string stepCode, int appTypeID)
        {
            if (this.Request.QueryString["AppID"] != null)
            {
                int appid = Convert.ToInt32(this.Request.QueryString["AppID"]);
                this.lblRunFlowActorsName.Text = this.GetActorsOfCurrentStep(stepCode, appTypeID, appid);
            }
            else
            {
                //AppID为空，默认StepName
                this.lblRunFlowActorsName.Text = description;
            }
        }

        private string GetActorsOfCurrentStep(string stepName, int appType, int appID)
        {
            string actors = string.Empty;

            IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            //Get actor info by step
            DataTable table = queryService.GetRoleAndEmpForStep(stepName, appType, appID);

            if (table != null && table.Rows.Count > 0)
            {
                DataRow[] rows = table.Select();
                IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;

                if (!string.IsNullOrEmpty(rows[0]["EmployeeNo"].ToString()))
                {
                    Employee employee = userService.GetUserByID(rows[0]["EmployeeNo"].ToString());
                    actors = employee.NameEN;
                }
                else
                {
                    IList list = userService.GetUserByRole((int)rows[0]["RoleID"]);
                    for (int i = 0; i < list.Count; i++)
                    {
                        BEGDC.CC.Entity.UserRole userRole = (BEGDC.CC.Entity.UserRole)list[i];
                        Employee employee = userRole.Employee;
                        actors += employee.NameEN + ",";
                    }
                    actors = actors.Substring(0, actors.Length - 1);
                }
            }
            return actors;
        }
    }
}
